<?php
declare(strict_types=1);

namespace Service\GoodsPointsService;

use Service\Code\Normal;
use Service\BaseService;
use App\Model\BbcModel\GoodsPointsLog;
use App\Model\BbcModel\GoodsPointsConfig;
use App\Model\BbcModel\Member;
use App\Model\BbcModel\Order;

class GoodsPointsService extends BaseService
{
    /**
     * 新增购物返积分日志
     * @param int $cid
     * @param int $mid
     * @param int $mn_sid
     * @param int $points
     * @param int $type
     * @param string $remark
     * @param string $sn
     * @param string $manager_name
     * @return type
     */
    public function addGoodsPointsChangLog(int $cid,int $mid,int $mn_sid, $points,int $type,string $remark,string $sn='',string $manager_name='')
    {
        $points_data = [
            'cid'       => $cid,
            'mid'       => $mid,
            'type'      => $type,
            'points'    => $points,
            'mn_sid'    => $mn_sid,
            'cd'        => time(),
            'remark'    => $remark,
            'sn'        => $sn,
            'manager_name'=>$manager_name
        ];
        return GoodsPointsLog::instance()->add($points_data);
    }

    /**
     * 处理扣减积分抵现
     * @param int $cid
     * @param int $mid
     * @param int $mn_sid
     * @param type $points
     * @param string $sn
     * @param string $remark
     * @return array
     */
    public function deductGoodsPoints(int $cid,int $mid,int $mn_sid,$points,string $sn,string $remark='') {
        $member_goods_pointsres = Member::instance()->where(['mid'=>$mid])->decrement('goods_points',$points);
        if(!$member_goods_pointsres){
            return Normal::returnCode(Normal::FAIL, '积分抵现扣减失败');
        }
        $member_goods_points_use_res = Member::instance()->where(['mid'=>$mid])->increment('goods_points_use',$points);
        if(!$member_goods_points_use_res){
            return Normal::returnCode(Normal::FAIL, '积分抵现扣减,历史使用失败');
        }
        $pointslog=$this->addGoodsPointsChangLog($cid, $mid, $mn_sid, $points, 0,$remark , $sn);
        if(!$pointslog){
            return Normal::returnCode(Normal::FAIL, '积分抵现扣减,变动记录失败');
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }
    
     /**
     * 处理增加积分抵现
     * @param int $cid
     * @param int $mid
     * @param int $mn_sid
     * @param type $points
     * @param string $sn
     * @param string $remark
     * @return type
     */
    public function addGoodsPoints(int $cid,int $mid,int $mn_sid,$points,string $sn,string $remark='') {
        $member_goods_pointsres = Member::instance()->where(['mid'=>$mid])->increment('goods_points',$points);
        if(!$member_goods_pointsres){
            return Normal::returnCode(Normal::FAIL, '积分抵现扣减失败');
        }
        $member_goods_points_use_res = Member::instance()->where(['mid'=>$mid])->increment('goods_points_history',$points);
        if(!$member_goods_points_use_res){
            return Normal::returnCode(Normal::FAIL, '积分抵现扣减,历史使用失败');
        }
        $pointslog=$this->addGoodsPointsChangLog($cid, $mid, $mn_sid, $points, 1,$remark , $sn);
        if(!$pointslog){
            return Normal::returnCode(Normal::FAIL, '积分抵现扣减,变动记录失败');
        }
        return Normal::returnCode(Normal::SUC, '处理完成');
    }
    
    /**
     * 计算可返积分
     * @param int $cid
     * @param int $mid
     * @param array $extra
     * @return int
     */
    public function dealReturnGoodsPoints(int $cid,int $mid,array $extra=[]) {
        $return_goods_points=0;
        $return_parent_points=0;
        $return_points_data=[
            'return_goods_points'=>0,
            'return_parent_points'=>0,
        ];
        if($mid<=0||empty($mid)){
            return $return_points_data;
        }
        $pointsConfig= GoodsPointsConfig::instance()->info(['cid'=>$cid]);
        if(empty($pointsConfig)){
            return $return_points_data;
        }
        if($pointsConfig['store_status']==0){//线下收银是否开启积分
            return $return_points_data;
        }
        if($pointsConfig['return_points_store_status']==0){
            return $return_points_data;
        }
        $goodsListMap=$extra['goodsListMap'];
        $orderGoods=$extra['orderGoods'];
        $return_points_type=$pointsConfig['return_points_type'];
        $return_points_goods=$pointsConfig['return_points_goods'];
        $return_base_money=$pointsConfig['return_base_money'];
        $return_points=$pointsConfig['return_points'];
        $points_limit=$pointsConfig['points_limit'];
        $store_return_ratio=$pointsConfig['store_return_ratio'];
        $store_return_invite=$pointsConfig['store_return_invite'];
        foreach ($orderGoods as $key => $value) {
            $current=0;
            $current_return_parent_points=0;
            $goodsTotalPrice= bcadd((string)$value['price_tax'],(string) $value['price_pay'],2);
            if($return_points_goods==2&&$goodsListMap[$value['goods_id']]['return_points']==0){
                continue;
            }
            if($return_points_type==1){//价格
                if($return_base_money>0){
                    $base_money= floor(bcdiv((string)$goodsTotalPrice, (string)$return_base_money,2));
                    $current= bcmul((string)$base_money,(string) $return_points,2);
                }
            }elseif($return_points_type==0){//个数
                $current= bcmul((string)$value['num'],(string) $return_points,2);
            }elseif($return_points_type==2){
                $current= bcmul((string)$goodsTotalPrice,(string) $store_return_ratio,2);
                if($store_return_invite==1){
                    $current_return_parent_points=bcmul((string)$goodsTotalPrice,(string) $pointsConfig['store_return_invite_ratio'],2);
                    $return_parent_points=bcadd((string)$return_parent_points,(string) $current_return_parent_points,2);
                }
            }
            $return_goods_points= bcadd((string)$return_goods_points,(string) $current,2);
        }
        $time=time();
        $begintime= strtotime(date('Y-m-d',$time));
        $totalPoints= Order::instance()->where('mid',$mid)->where('status','>=','20')->whereBetween('cd',[$begintime,$time])->sum('return_goods_points');
        if($totalPoints>=$points_limit){
            $return_goods_points=0;
        }else{
            $sendMax= bcsub((string)$points_limit, (string)$totalPoints,2);
            if($sendMax<$return_goods_points){
                $return_goods_points= $sendMax;
            }
        }
        
        $return_points_data=[
            'return_goods_points'=>$return_goods_points,
            'return_parent_points'=>$return_parent_points,
        ];
        return $return_points_data;
    }

    /**
     * 获取店铺利润包含积分支付金额，1-包含积分
     * @param $cid
     * @return int|mixed
     */
    public function storeProfitType($cid)
    {
        $info = GoodsPointsConfig::instance()->info(['cid'=>$cid]);
        $storeProfitType = $info['store_profit_type'] ?? 1;

        return $storeProfitType;
    }
}
